/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 2/25/2010
*/

public without sharing class IOGQuickClosePageController {
	private final Case cs;
	public String comments {get; set;} 
	public String saveResult {get; set;}
	
	public IOGQuickClosePageController(ApexPages.StandardController stdController){
		this.cs = (Case) stdController.getRecord();
		this.cs.AFrontier_Issue__c = null;
		this.cs.AFrontier_Reason__c = null;
		this.saveResult = 'false';
	}
	
	public PageReference saved() {
		Boolean rst = true;
		
		Savepoint sp = Database.setSavepoint();
		
		rst = validateRequiredFields();
		if(rst) {rst = createCompleteInquries();}
		if(rst) {rst = closeIncidents();}
		if(rst) {rst = insertCaseComments();}
		this.saveResult = '' + rst;
		if(!rst){
			Database.rollback(sp);
		}
		return null;
	}
	
	private Boolean validateRequiredFields(){
		Boolean rst = true;
		if(this.cs.AFrontier_Issue__c == null){
			addError(' Issue: You must enter a value ');
			rst = false;
		}
		if(this.cs.AFrontier_Reason__c == null){
			addError(' Reason: You must enter a value ');
			rst = false;
		}
		if(this.cs.CSS_ProductFamily__c == null){
			addError(' Product: You must enter a value ');
			rst = false;
		}
		return rst;
	}
	
	private Boolean closeIncidents(){
		this.cs.AFrontier_Issue__c = null;
		this.cs.AFrontier_Reason__c = null;
		this.cs.CSS_CRF_RequestType__c = 'Inquiry';
		this.cs.Status = 'Closed';
		try{
			update this.cs;
		}catch(Exception ex){
			addError(ex.getMessage());
			GeneralConstants.mailAnyExceptionToMe('IOGQuickClosePageController', 'Quick Close Incident fail', ex);
			return false;
		}
		return true;
	}
	
	private Boolean createCompleteInquries(){
		if(this.cs.CSS_ProductFamily__c != null){
			List<Case> newstubs = new List<Case>();
			List<Case> stubs = [select Product_Family__c from Case where ParentId =: this.cs.Id];
			Set<String> products = new Set<String>();
			for(Case c : stubs){
				products.add(c.Product_Family__c);
			}
			Case queriedcase = (Case) CustomCloneFunctionClass.queryObj('Case', this.cs.Id);
			String[] ss = this.cs.CSS_ProductFamily__c.split(';');
			for(String s : ss){
				if(!products.contains(s)){
					Case newcs = (Case) queriedcase.clone(false, true); // clear Id, deep clone
					setCaseFieldsToFixedvalues(newcs, s);
					newstubs.add(newcs);
				}
			}
			String error = null;
			try{
				insert newstubs;
			}catch(Exception ex){
				if(ex.getMessage() != null && ex.getMessage().contains('INVALID_EMAIL_ADDRESS')){
					for(Case c : newstubs){
						c.SuppliedEmail = 'null@null.null';
					}
					try{
						insert newstubs; // try again
					}catch(Exception e){	
						addError(e.getMessage());
						GeneralConstants.mailAnyExceptionToMe('IOGQuickClosePageController', 'Quick Close insert New Inquiries fail inside', e);
						return false;					
					}					
				}else{
					addError(ex.getMessage());
					GeneralConstants.mailAnyExceptionToMe('IOGQuickClosePageController', 'Quick Close insert New Inquiries fail outside', ex);
					return false;
				}
			}
		}
		return true;	
	}
	
	private void setCaseFieldsToFixedvalues (Case c, String product){	
		c.ParentId = this.cs.Id;
		c.Product_Family__c = product;
		c.CSS_ProductFamily__c = null;
		c.IR_Priority__c = 'Standard';
		c.RecordTypeId = RecordTypeHelper.GetRecordTypeID('Case', 'IOG Inquiry');
		c.Status = 'Complete';
		c.AFrontier_Issue__c = this.cs.AFrontier_Issue__c;
		c.AFrontier_Reason__c = this.cs.AFrontier_Reason__c;
		c.SuppliedEmail = GeneralConstants.checkAndTransformWebEmail(c.SuppliedEmail);			
	}
	
	private Boolean insertCaseComments(){
		if(this.comments != null && this.comments.length() > 0){
			CaseComment cc = new CaseComment();
			cc.CommentBody = this.comments;
			cc.IsPublished = false;
			cc.ParentId = this.cs.Id;
			try{
				insert cc;
			}catch(Exception ex){
				addError(ex.getMessage());
				GeneralConstants.mailAnyExceptionToMe('IOGQuickClosePageController', 'Quick Close insert New Case comments fail', ex);
				return false;
			}
		}
		this.comments = null;
		return true;
	}
	
	//    Method adds an Error message to the page
    private void addError(String errorMsg){         
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,errorMsg);               
        ApexPages.addMessage(msg);
    } 
        
    //    Method adds an Warning message to the page
    private void addWarning(String warningMsg){         
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.WARNING,warningMsg);               
        ApexPages.addMessage(msg);
    }  
}